package com.fanghaoran.notes.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @Author: win11
 * @Date: 2023/04/14/22:03
 * @Description: 密码加密类
 */
public class EncryptUtil {

    /**
     * 加盐加密的方法
     */
    public static byte[] hashPassword(String password) {
        try {
            // 拼接密码和盐
            byte[] salt=Constants.SALT;
            byte[] passwordBytes = password.getBytes();
            byte[] passwordAndSalt = new byte[passwordBytes.length + salt.length];
            System.arraycopy(passwordBytes, 0, passwordAndSalt, 0, passwordBytes.length);
            System.arraycopy(salt, 0, passwordAndSalt, passwordBytes.length, salt.length);

            // 使用 SHA-256算法进行哈希
            MessageDigest md = MessageDigest.getInstance("SHA-256");

            // 执行多次哈希，并返回最终结果
            byte[] hashedBytes = passwordAndSalt;
            for (int i = 0; i < Constants.ITERATION_COUNT; i++) {
                //digest计算得出加密后的数据
                hashedBytes = md.digest(hashedBytes);
            }
            return hashedBytes;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException("Hashing the password failed", e);
        }
    }

}
